package com.example.tools

import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import androidx.core.content.ContextCompat
import com.example.dingdingtools.MyAccessibilityService

/**
 * 权限检查
 */
object CheckPermissionsUtils {

    /**
     * 检查无障碍功能是否开启如果没有开启则直接跳转权限开启
     */
    fun checkAccessibilityPermission(context: Context) {
        if (!isAccessibilitySettingsOn(
                context,
                MyAccessibilityService::class.java
            )
        ) {
            openSettingAccessibility(
                context
            )
        }
    }

    /**
     * 判断否有开启无障碍功能
     */
    fun isAccessibilitySettingsOn(
        mContext: Context,
        clazz: Class<out AccessibilityService?>
    ): Boolean {
        var accessibilityEnabled = 0
        val service = mContext.packageName + "/" + clazz.canonicalName
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                mContext.applicationContext.contentResolver,
                Settings.Secure.ACCESSIBILITY_ENABLED
            )
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
        }
        val mStringColonSplitter = TextUtils.SimpleStringSplitter(':')
        if (accessibilityEnabled == 1) {
            val settingValue = Settings.Secure.getString(
                mContext.applicationContext.contentResolver,
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
            )
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue)
                while (mStringColonSplitter.hasNext()) {
                    val accessibilityService = mStringColonSplitter.next()
                    if (accessibilityService.equals(service, ignoreCase = true)) {
                        return true
                    }
                }
            }
        }
        return false
    }

    /**
     * 打开设置界面的无障碍功能
     */
    fun openSettingAccessibility(context: Context) {
        val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        ContextCompat.startActivity(context, Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), null)
    }

    /**
     * 判别是否有悬浮框权限
     *
     * @param context
     */
    fun ckeckPermissionPopWindow(context: Context): Boolean {
        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(context)) {
                val intent = Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + context.packageName)
                )//应用的包名，可直接跳转到这个应用的悬浮窗设置；
                context.startActivity(intent);
            } else {
                return true
            }
        }
        return false
    }
}